<?php
/**
 * index..php
 *
 * - browse on uploaded pcap files 
 * - create new folder
 * - re-upload new file
 *
 *
 * LICENSE: 
 * This file is part of EasyShark.
 *
 *   EasyShark is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   EasyShark is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with EasyShark.  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author     Balazs Barcsik <balazs.barcsik@gmail.com>
 * @license    http://www.gnu.org/licenses/gpl.txt
 */
/*
Basic browser capabilites from:
http://neilang.com/entries/php-explore-your-server-through-a-php-file-browse/
*/
?>
<html>
<head>
  <title>EasyShark</title>
  <style type="text/css">
    .error{ color:red; font-weight:bold; }
  </style>
</head>
<body>

<?php

include 'config.php';

function f_storeFile($fileToStore, $directory) {

	$allowedExts = array("pcap", "pcapng", "cap");

	$temp = explode(".", $fileToStore["name"]);
	$extension = end($temp);
	if ((($fileToStore["type"] == "application/octet-stream")
			|| ($fileToStore["type"] == "application/vnd.tcpdump.pcap"))
			//&& ($_FILES["file"]["size"] < 20000)
	&& in_array($extension, $allowedExts))
	{
		if ($fileToStore["error"] > 0)
		{
			echo "Return Code: " . $fileToStore["error"] . "<br>";
		}
		else
		{
			echo "Upload: " . $_FILES["file"]["name"] . "<br>";
			echo "Type: " . $_FILES["file"]["type"] . "<br>";
			echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
			echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
			echo "path to store: "."/".$directory;

			if (file_exists($directory."/" . $fileToStore["name"]))
			{
				echo $fileToStore["name"] . " already exists. ";

			}
			else
			{
				move_uploaded_file($fileToStore["tmp_name"],
				$directory."/" . $fileToStore["name"]);
				//echo "Stored in: " . "/tmp/" . $_FILES["file"]["name"]."<br>";
			}


		}
		return $directory."/".$fileToStore["name"];

	} else {
		echo "Invalid file";
		echo "Upload: " . $fileToStore["name"] . "<br>";
		echo "Type: " . $fileToStore["type"] . "<br>";
		echo "Size: " . ($fileToStore["size"] / 1024) . " kB<br>";
		echo "Temp file: " . $fileToStore["tmp_name"] . "<br>";
		echo "path to store: ".$directory."/".$fileToStore["name"];
		return "";
	}
}

// Explore the files via a web interface.   
  $script = basename(__FILE__); // the name of this script
  $parent_root_folder = dirname($root_folder);
  
  $relative_path   = !empty($_REQUEST['path']) ? $_REQUEST['path'] : '';

 
  if($relative_path != '') {
  	$path = $root_folder.'/'.$relative_path;
  } else {
  	$path = $root_folder;
  }
  
  if(!empty($_GET['create_folder'])) {
  	$name = $path.'/'.$_GET['create_folder'];
  	
  	
  		if(!is_dir($name)){
  			echo "crated folder with name: ".$name;
  			mkdir($name);
  		} else {
  			echo "Error - folder already exsists";
  		}
  }
  
  //pcap file uploaded
  if($_FILES) {
  	if ($_FILES["file"] and $_FILES["file"]["name"] != "") {
  		$relative_path = $_POST["path"];
  		f_storeFile($_FILES["file"], $root_folder.'/'.$relative_path);
  	} 
  	
  	$relative_path = $_POST["path"];
  }
  
  
  echo "<h3>Browsing Location: {$relative_path}</h3>";
  
  $directories = array();
  $files       = array();
  
  // Check we are focused on a dir
  if (is_dir($path)){
    chdir($path); // Focus on the dir
    if ($handle = opendir('.')){
      while (($item = readdir($handle)) !== false) {
        // Loop through current directory and divide files and directorys
        if(is_dir($item)){
          array_push($directories, realpath($item));
        }
        else{
          array_push($files, ($item));
        }
      }
      
      closedir($handle); // Close the directory handle
    }
    else {
      echo "<p class=\"error\">Directory handle could not be obtained.</p>";
    }
  }
  else{
    echo "<p class=\"error\">Path is not a directory</p>";
  }
  
  // List the directories as browsable navigation
  echo "<h2>Navigation</h2>";
  echo "<ul>";
  foreach($directories as $directory){
  	//FIXME file1 should not add if not exist
  	$relative_dir = '';
  	if($directory != $root_folder) {
  		$relative_dir = str_replace($root_folder.'/', '', $directory);
  	}
  	$display_dirName = basename($directory);
  	if(dirname($path) == $directory) {
  		$display_dirName = '..';
  	} 
    echo ($directory != $path && $directory != $parent_root_folder) ? '<li><a href="'.$script.'?path='.$relative_dir.'">'.$display_dirName.'</a></li>' : '';
  }
  echo "</ul>";
  
  echo "<h2>Files</h2>";
  echo "<ul>";
  foreach($files as $file){
    // Comment the next line out if you wish see hidden files while browsing
    if(preg_match("/^\./", $file) || $file == $script){continue;} // This line will hide all invisible files.
    
   
    
    $relative_path_with_file = $file;
    if($relative_path != "" && $relative_path != ".") {
    	$relative_path_with_file = $relative_path.'/'.$file;
    }
    	
        	
    	echo '<li><a href="display.php?file1='.$relative_path_with_file. '">' . $file . '</a> | <a href="download.php?file='.$relative_path_with_file.'">download</a></li>';
    
  }
  
  echo "</ul>";
  print "<p/>";
  
  print '	<form action="index.php" method="post"';
  print '	enctype="multipart/form-data">';
  print '	<label for="file">Upload file: </label><br>';
  print '	<input type="file" name="file" id="file"><br>';
  print   '<input type="hidden" name="path" value="'. $relative_path.'">';
  print '	<input type="submit" name="submit" value="Upload">';
  print '	</form>';
  
  print	'<form action="index.php">';
    
  print	'Folder name: <input type="text" value="" name="create_folder"><br/>';
  print   '<input type="hidden" name="path" value="'. $relative_path.'">';
  print	'<input type="submit" value="Create">';
  print	'</form>';
print '
 

<div style="background-color:#efefe1;">
            <p><a href="http://code.google.com/p/easyshark/">EasyShark</a> server</p>
        </div>
</body></html>';
?>

</body>
</html>
